import java.io.*;
import java.util.Scanner;

public class demo3 {
    private static void scan(File currentFile,String key){
        if (!currentFile.isDirectory()){
            return;
        }

        File[] files=currentFile.listFiles();
        if (files.length==0||files==null){
            return;
        }
        for (File f:files) {
            if (f.isFile()){
                doSearch(f,key);
            }else{
                scan(f,key);
            }
        }
    }

    private static void doSearch(File f,String key){
        StringBuilder stringBuilder=new StringBuilder();

        try(Reader reader=new FileReader(f)) {
            char[] buffer=new char[1024];
            while(true){
                int n= reader.read(buffer);
                if (n==-1){
                    break;
                }
                String s=new String(buffer,0,n);
                stringBuilder.append(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (stringBuilder.indexOf(key)==-1){
            //未找到
            return;
        }
        System.out.println("找到了匹配的文件："+f.getAbsolutePath()  );
    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入你要搜索的路径：");
        String rootPath=sc.nextLine();
        File rootFile=new File(rootPath);
        if (!rootFile.isDirectory()){
            System.out.println("要搜索的路径有误");
            return;
        }
        System.out.println("请输入你要查询的内容");
        String key=sc.next();

        scan(rootFile,key);
    }
}
